<template>
  <div id="uploadContainer"></div>
</template>

<script setup lang="ts">
import MaUploader, { Message } from '@/plugins/LargeFileUpload/init'

import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/api/http'
import { onMounted } from 'vue'
import CustomViewContainer from '@/components/CustomViewContainer.vue'

let ML: MaUploader

async function init() {
  // 创建上传队列，最大并发 6，最多重试 3 次
  ML = new MaUploader({
    // 挂载容器
    el: document.getElementById('uploadContainer') as HTMLElement,
    // 自定义视图容器，可通过此配置自定义UI
    // customViewContainer: CustomViewContainer,
    options: {
      // 分片大小
      chunkSize: 1024 * 1024 * 10, // 默认 10MB
      // 上传类型
      // accept: '.jpg, .jpeg, .png, .mp4',
      accept: '*',
      // 分片队列最大并发数
      queueMax: 3,
      // 分片最大重试次数
      retryMax: 3,
      // 一次上传的最大文件限制,默认这里设置2GB
      maxTotalSize: 1024 * 1024 * 1024 * 2,
      // 是否允许选择文件夹
      folder: true,
    },
    // 自定义钩子
    hooks: {},
  })

  // 监听文件读取完成事件
  ML.on('onFileSelected', async (data: any) => {
    Message('success', '添加文件成功')
    return data
  })
  // 监听文件分片事件
  ML.on('onFileChunking', async (data: any) => {
    // Message('success', '文件分片成功')
    return data
  })
  // 监听文件哈希值计算完成事件
  ML.on('onFileHashed', async (data: any) => {
    // Message('success', '文件哈希值计算完成')
    return data
  })
  // 监听文件添加到上传队列事件
  ML.on('onFileAdded', async (data: any) => {
    // Message('success', `分片添加队列成功,已添加${data.taskCount}个任务`)
    return data
  })
  // 监听文件分片上传成功事件
  ML.on('onChunkUploaded', async (data: any) => {
    // Message('success', '分片上传成功')
    return data
  })
  // 监听文件分片合并成功事件
  ML.on('onChunkMergeEnd', async (data: any) => {
    // Message('success', '分片合并成功')
    return data
  })
  // 监听所有文件上传结束事件
  ML.on('onAllComplete', async (data: any) => {
    Message('success', '所有文件上传完成')
    return data
  })

  // 检查分片上传接口
  ML.on('onCheckChunksByRequest', (data: any, next) => {
    http
      .post('/api/verify_chunk', {
        chunkSize: data.chunkSize,
        fileHash: data.fileHash,
        fileName: data.fileName,
        totalChunks: data.chunkList.length,
      })
      .then((res: any) => {
        if (res.code === 200) {
          next({
            isExist: res.data.isComplete,
            existList: res.data.existList,
          })
        }
      })
  })

  // 上传分片请求
  ML.on(
    'onUploadChunkByRequest',
    async (
      data,
      onUploadProgress: (e: any) => void,
      thenCallback?: (res: any) => void,
      catchCallback?: (err: any) => void,
    ) => {
      const formData = new FormData()
      Object.keys(data.params).forEach((item) => {
        formData.append(item, data.params[item])
      })

      return http
        .post('/api/upload_chunk1', formData, {
          onUploadProgress,
        })
        .then((res: any) => {
          // debugger
          if (res.code === 200) {
            thenCallback && thenCallback(res)
          }
        })
        .catch((err) => {
          catchCallback && catchCallback(err)
        })
    },
  )

  // 监听分片上传完成事件，发起合并分片请求
  ML.on('onMergeChunkByRequest', async (data: any) => {
    try {
      const res: any = await http.post('/api/merge_chunk', {
        size: data.chunkSize,
        fileHash: data.fileHash,
        fileName: data.fileName,
        totalChunks: data.chunkList.length,
      })

      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: `文件：${data.fileName}上传成功`,
        })
      }
      return res
    } catch (error) {
      ElMessage({
        type: 'error',
        message: `文件：${data.fileName}上传失败`,
      })
    }
  })

  console.log('码喽实例', ML)
}
onMounted(() => {
  init()
})

function test() {
  http.get('/api/test').then((res) => {
    // debugger
    console.log(res)
  })
}
</script>
